<?php

namespace app\api\controller;

use app\admin\model\Medicine;
use Throwable;
use app\common\controller\Backend;

/**
 * 配伍禁忌
 */
class Peiwu extends Backend
{
    /**
     * Peiwu模型对象
     * @var object
     * @phpstan-var \app\admin\model\Peiwu
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id'];

    protected array $withJoinTable = ['m1Table', 'm2Table'];

    protected string|array $quickSearchField = ['id', 'name'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Peiwu();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['m1Table' => ['name'], 'm2Table' => ['name']]);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
    public function listall()
    {
        $params = $this->request->param();
        $query = $this->model->where([]);
        $ids = $params['ids'] ?? '';
        $ids = explode(',', $ids);
        $titile = Medicine::where('id', 'in', $ids)->column('name');
        $titile = implode('&', $titile);
        // $query->where(function ($query) use ($ids) {
        //     $query->where('m1', 'in', $ids)->whereOr('m2', 'in', $ids);
        // });
        // if (count($ids) == 1 && ($id = $ids[0])) {
        //     $query->whereRaw(" m1 = '$id' or m2 = '$id' ");
        // } else if (count($ids) >= 2) {
        //     $id1 = $ids[0];
        //     $id2 = $ids[1];
        //     $query->whereRaw(" (m1 = '$id1' and m2 = '$id2') or (m1 = '$id2' and m2 = '$id1') ");
        // if (count($ids) == 1) {
        //     $id = $ids[0];
        //     $query->where(function ($query) use ($id) {
        //         $query->where('m1', '=', $id)->orWhere('m2', '=', $id);
        //     });
        // } elseif (count($ids) == 2) {
        //     $id1 = $ids[0];
        //     $id2 = $ids[1];
        //     $query->where(function ($query) use ($id1, $id2) {
        //         $query->where(['m1' => $id1, 'm2' => $id2])->orWhere(['m1' => $id2, 'm2' => $id1]);
        //     });
        // } elseif (count($ids) > 2) {
        //     $combinations = [];
        //     foreach ($ids as $key => $id1) {
        //         for ($i = $key + 1; $i < count($ids); $i++) {
        //             $id2 = $ids[$i];
        //             $combinations[] = ['m1' => $id1, 'm2' => $id2];
        //             $combinations[] = ['m1' => $id2, 'm2' => $id1];
        //         }
        //     }
        //     if (!empty($combinations)) {
        //         $query->where(function ($query) use ($combinations) {
        //             foreach ($combinations as $index => $combination) {
        //                 if ($index == 0) {
        //                     $query->where($combination);
        //                 } else {
        //                     $query->orWhere($combination);
        //                 }
        //             }
        //         });
        //     }
        // }
        $query->where(function ($query) use ($ids) {
            if (count($ids) == 1) {
                $id = $ids[0];
                $query->where(function ($query) use ($id) {
                    $query->where('m1', $id)->whereOr('m2', $id);
                });
            } elseif (count($ids) == 2) {
                $id1 = $ids[0];
                $id2 = $ids[1];
                $query->where(function ($query) use ($id1, $id2) {
                    $query->where(function($query) use ($id1,$id2){
                        $query->where(['m1' => $id1, 'm2' => $id2]);
                    })
                    ->whereOr(function($query) use ($id1,$id2){
                        $query->where(['m1' => $id2, 'm2' => $id1]);
                    });
                });
                // echo $query->fetchSql()->select();
            } else {
                $query->where(function ($query) use ($ids) {
                    if (count($ids) == 1) {
                        $id = $ids[0];
                        $query->where('m1', $id)->whereOr('m2', $id);
                    } else {
                        $combinations = [];
                        for ($i = 0; $i < count($ids); $i++) {
                            for ($j = $i + 1; $j < count($ids); $j++) {
                                $combinations[] = function ($query) use ($ids, $i, $j) {
                                    $query->where(function ($query) use ($ids, $i, $j) {
                                        $query->where(['m1' => $ids[$i], 'm2' => $ids[$j]]);
                                    })->whereOr(function ($query) use ($ids, $i, $j) {
                                        $query->where(['m1' => $ids[$j], 'm2' => $ids[$i]]);
                                    });
                                };
                            }
                        }
                
                        foreach ($combinations as $combination) {
                            $query->whereOr($combination);
                        }
                    }
                });
            }
        });

        // }
        $list = $query->order('id desc')->select();
        $list = $list ? $list->toArray() : [];
        foreach ($list as &$item) {
            // $item['name'] = 
            $name = '';
            // var_dump($item);
            // if(!$item['m1'])
            // if (count($ids) == 1 && $item['m1'] == $ids[0]) $name = $item['m2_name'];
            // if (count($ids) == 1 && $item['m2'] == $ids[0]) $name = $item['m1_name'];
            // if (count($ids) >= 2) 
            $name = $item['m1_name'] . '&' . $item['m2_name'];
            $item['name'] = $name;
        }
        return json(['code' => 0, 'msg' => '获取成功', 'data' => $list, 'title' => $titile]);
    }
}
